<div class="b-container clear">
  <div class="b-content">
    <div class="b-content__item-left">
      <div class="b-content-item__head">
        <div class="b-content-item-head__title">
          <h1>Найденное</h1>
        </div>
      </div>
      <div class="b-content-item__content" id="content-left"></div>
    </div>
    <div class="b-content__item-right">
      <div class="b-content-item__head">
        <div class="b-content-item-head__title">
          <h1>Потерянное</h1>
        </div>
      </div>
      <div class="b-content-item__content" id="content-right"></div>
    </div>
  </div>
</div>
<script>
$(document).ready(function(){
  var catM = [];
  var catT = [];
  
  function getItemsForList(){
    catM = [];
    catT = [];
    $.getJSON('<?php echo base_url();?>category/read/')
    .done(function(json){
      catM = json;
      catT = [];
      getList(catM, 12);
      getObject(catT, "#content-left");
      catT = [];
      getList(catM, 27);
      getObject(catT, "#content-right");
      });
    }
    
      
      function getList(array,level){
        $.each(array, function(key, data){
          if(data.parent == level){
            catT.push(getList(array, data.id));
          }
        });
        return level;
      }
      
      function getObject(param, selector){
          $.post('<?php echo base_url();?>item/readWithCatId/', {data : param})
            .done(function(result){
              var obj = $.parseJSON(result);
              buildContent(obj, selector);
            });
      }
      
      function buildContent(arrObj, selector){
        var str = '';
        $.each(arrObj, function(key, data){
          str += '<a href="<?php echo base_url();?>item/post/'+data.id+'"><div class="b-content-item-list__item"><div class="b-content-item-list-item-redpin"></div><div class="b-content-item-list-text">'+data.name+' от '+data.timeAdd+'</div></div></a>';
        });
        str += '';
        $(selector).append(str);
      }
      
      function buildCreateForm(){
       $.getJSON('<?php echo base_url();?>category/read/',function(json){
         var string  ='';
         string += '<div id="view_container">';
         string += '<div id="view_edit" style="background: grey;">';
         string += '<div id="preloader"><img src="<?php echo base_url();?>img/preloader.gif"></div>';
         string += '<form id="create_item_form" action="<?php echo base_url();?>item/create/" method="post" style="display: none;">';
         string += '<div class="b-header-form-item-left"><label>Название</label></div>';
         string += '<div class="b-header-form-item-right"><input type="text" required name="name" placeholder="Название"></div>';
         string += '<div class="b-header-form-item-left"><label>Категория</label></div>';
         string += '<div class="b-header-form-item-right">'+createSelect('category', json, 0)+'</div>';
         string += '<div class="b-header-form-item-left"><label>Где и Когда</label></div>';
         string += '<div class="b-header-form-item-right"><textarea  name="locationAndDate" placeholder="Где и Когда" required></textarea></div>';
         string += '<div class="b-header-form-item-left"><label>Опишите подробнее</label></div>';
         string += '<div class="b-header-form-item-right"><textarea name="description" placeholder="Опишите подробнее" required></textarea></div>';
         string += '<div class="b-header-form-item-left"><label>Контактные данные</label></div>';
         string += '<div class="b-header-form-item-right"><textarea name="userInfo" placeholder="Контактные данные" required></textarea></div>';
         string +='<div class="b-header-form-item"><input id="submit" type="submit" value="Отправить"></div></form>';
         string += '</div>';
         $('.b-header-slide-inner').html('');
         $('.b-header-slide-inner').append(string);
         //init
         $('select[name="category"]').after($(createSelect('categoryId', json, parseInt($('select[name="category"]').val()))));
         //change
         $('select[name="category"]').change(function(){
           $('select[name="categoryId"]').remove();
           $('select[name="category"]').after($(createSelect('categoryId', json, parseInt($('select[name="category"]').val()))));
         });
         //прячем прелодер
         $('#preloader').hide();
         // показываем форму
         $('#create_item_form').show();
         //ловим событие отправки сообщения
         $('#create_item_form').submit(function (event){
            // отменяем стандартную отправку данных
            event.preventDefault();
            $('#create_item_form').hide();
            $('#preloader').show();
            var posting =  $.post('<?php echo base_url();?>item/create/', {
                                     name: ''+$('input[name="name"]').val(),
                                     categoryId: ''+$('select[name="categoryId"]').val(),
                                     locationAndDate: ''+$('textarea[name="locationAndDate"]').val(),
                                     description: ''+$('textarea[name="description"]').val(),
                                     userInfo: ''+$('textarea[name="userInfo"]').val() 
                                   });
            
            posting.done(function (data){
            $('#preloader').hide();
            var anser = JSON.parse(data);
            if(anser.code){
                $('.b-header-slide').html('Добавить находку/пропажу');
                $('.b-header-slide-inner').slideUp("slow");
                $('.b-header-slide-inner').hide("slow");
             clearItemList();
             getItemsForList();
             buildCreateForm();
            }
          });
         });
      });      
    }
function createListOption(list, level,idSelected){
    if(typeof list != "undefined" ){
      var elements ='';
      var select = '';
    $.each(list, function(key,data){
      if(data.id ==  idSelected && idSelected != 'undefined'){
        select = 'selected';
      }
      else select = '';
      if(data.parent == level)
        elements += '<option value="'+data.id+'" '+select+'>'+data.name+'</option>';
    });
    return elements;
  }
  }
function createSelect(name,list,level,idSelected){
    if(typeof name != 'undefined'){
      return '<select name="'+name+'">'+createListOption(list,level,idSelected)+'</select>';
    }
  }
  
  function clearItemList(){
        $('#content-right').html('');
        $('#content-left').html('');
      }
  
  
  $('.b-header-slide').click(function(){
    if($('.b-header-slide-inner').is(':hidden')){
      
      $('.b-header-slide-inner').slideDown("slow");
      $('.b-header-slide-inner').show("slow");
      $('.b-header-slide').html('Закрыть');
    }
    else{
      $('.b-header-slide').html('Добавить находку/пропажу');
      $('.b-header-slide-inner').slideUp("slow");
      $('.b-header-slide-inner').hide("slow");
    }
  });
      buildCreateForm();
      getItemsForList();
      
      
});
</script>